package top.ieei.demo.tftp;

/**
 * TFTP确认响应包<br>
 * @author xiecongshu
 */
public class TftpAck extends TftpPacket
{
    
    /**
     * 数据块编号索引：2
     */
    protected static final int INDEX_BLOCKNUM = 2;
    
    /**
     * ACK确认响应操作码 ：4
     */
    public static final int OPCODE = 4;
    
    /**
     * 块编号
     */
    protected int blockNum = 0;
    
    /**
     * <默认构造函数>
     */
    public TftpAck()
    {
        this(0);
    }
    
    /**
     * <默认构造函数>
     */
    public TftpAck(int blockNum)
    {
        super();
        this.blockNum = blockNum % 65536;
    }
    
    /**
     * 通过UDP数据构建TFTP响应
     * @param tftpBytes UDP数据
     */
    public TftpAck(byte[] tftpBytes) throws TftpException
    {
        super(tftpBytes);
        blockNum = byteToInt(tftpBytes[INDEX_BLOCKNUM],
                tftpBytes[INDEX_BLOCKNUM + 1]);
    }
    
    /**
     * 获取块编号
     * @return int
     */
    public int getBlockNum()
    {
        return blockNum;
    }
    
    /**
     * 获取响应数据的字节数组<br>
     * 
     * @return byte[]
     */
    @Override
    public byte[] getBytes()
    {
        byte[] tftpBytes = new byte[MIN_PACKET_SIZE];
        
        // 加入两字节操作码
        tftpBytes[INDEX_OPCODE] = (byte) ((OPCODE >> 8) & 0xff);
        tftpBytes[INDEX_OPCODE + 1] = (byte) (OPCODE & 0xff);
        
        // 加入两字节块编号
        tftpBytes[INDEX_BLOCKNUM] = (byte) ((blockNum >> 8) & 0xff);
        tftpBytes[INDEX_BLOCKNUM + 1] = (byte) (blockNum & 0xff);
        return tftpBytes;
    }
    
    /**
     *获取操作码<br>
     * 
     * @return int
     */
    @Override
    public int getOpCode()
    {
        return OPCODE;
    }
    
}
